<template>
  <view class="navbar">
    <view
      v-for="(item, index) in navList"
      :key="index"
      class="nav-item"
      :class="{ current: tabCurrentIndex === item.key }"
      @click="tabClick(item.key)"
    >
      {{ item.text }}
    </view>
  </view>
  <view class="container">
    <Form
      v-show="tabCurrentIndex != '4'"
      :formOption="formOptions"
      ref="form"
      @onSubmit="onSubmit"
      :zyryList="zyryList"
      :jobType="jobType"
      :disabled="formDisabled"
      :zypList="zypList"
    >
      <template #aqcsinput1="{ formData, option }">
        <uni-forms-item>
          <template #label>
            <view style="border-top: 1px solid #333; font-size: 13px">
              与动火设备相连接的所有管线已断开，加盲板(
              <input
                type="text"
                class="input-num"
                v-model="formData.mbnum"
                :disabled="formDisabled"
              />)块，未采取水封或仅关闭阀门的方式代替盲板（监护人）
            </view>
          </template>
          <uni-data-checkbox
            v-model="formData.yesOrNo2"
            :localdata="[
              {
                value: '是',
                text: '涉及',
              },
              {
                value: '否',
                text: '不涉及',
              },
            ]"
            :multiple="false"
            :disabled="formDisabled"
          ></uni-data-checkbox>
        </uni-forms-item>
      </template>
      <template #aqcsinput2="{ formData, option }">
        <uni-forms-item>
          <template #label>
            <view style="border-top: 1px solid #333; font-size: 13px">
              现场配备灭火器(
              <input
                type="text"
                class="input-num"
                v-model="formData.mhqnum"
              />)台，灭火毯(
              <input type="text" class="input-num" v-model="formData.mhtnum" />
              )块，消防蒸汽带或消防水带(
              <input
                type="text"
                class="input-num"
                v-model="formData.fsdnum"
              />)（监护人）
            </view>
          </template>
          <uni-data-checkbox
            v-model="formData.yesOrNo8"
            :localdata="[
              {
                value: '是',
                text: '涉及',
              },
              {
                value: '否',
                text: '不涉及',
              },
            ]"
            :multiple="false"
            :disabled="formDisabled"
          ></uni-data-checkbox>
        </uni-forms-item>
      </template>
      <template #sckjinput="{ formData, option }">
        <uni-forms-item>
          <template #label>
            <view style="border-top: 1px solid #333; font-size: 13px">
              已配备作业应急措施：消防器材（
              <input
                type="text"
                class="input-num"
                v-model="formData.xfqcnum"
                :disabled="formDisabled"
              />）、救生绳（
              <input
                type="text"
                class="input-num"
                v-model="formData.jssnum"
                :disabled="formDisabled"
              />
              ）、气防装备（
              <input
                type="text"
                class="input-num"
                v-model="formData.qfsbnum"
                :disabled="formDisabled"
              />），盛有腐蚀性介质的容器作业现场已配备应急用冲洗水（监护人）
            </view>
          </template>
          <uni-data-checkbox
            v-model="formData.yesOrNo8"
            :disabled="formDisabled"
            :localdata="[
              {
                value: '是',
                text: '涉及',
              },
              {
                value: '否',
                text: '不涉及',
              },
            ]"
            :multiple="false"
          ></uni-data-checkbox>
        </uni-forms-item>
      </template>
      <template
        v-for="(item, index) in longLabelSlots"
        #[item]="{ formData, option }"
      >
        <uni-forms-item
          label=""
          :name="option.prop"
          :required="option.required"
          :rules="
            option.required
              ? [
                  {
                    required: true,
                    errorMessage: '字段为必填项',
                  },
                ]
              : []
          "
        >
          <template #label>
            <view style="border-top: 1px solid #333; font-size: 13px">
              {{ option.label }}
            </view>
          </template>
          <uni-data-checkbox
            v-model="formData[option.prop]"
            :localdata="option.optionItems"
            :multiple="option.type == 'checkbox'"
            @change="change(option.prop, $event)"
            :disabled="formDisabled"
          >
          </uni-data-checkbox>
        </uni-forms-item>
      </template>
      <template
        v-for="(item, index) in qianmingSlots"
        #[item]="{ formData, option }"
      >
        <uni-forms-item :label="option.label">
          <Qianming
            @change="changeQm(option, formData)"
            v-model="formData[option.prop]"
            :canvasId="option.prop + index"
            :disabled="formDisabled"
            :open="openQm"
          ></Qianming>
          <!-- :disabled="formDisabled || qmDisabled(option)" -->
        </uni-forms-item>
      </template>
    </Form>
    <view v-show="tabCurrentIndex == '4'" style="padding-top: 40px">
      <button
        @click="addQtjc"
        type="primary"
        style="position: fixed; top: 60px; right: 10vw; z-index: 9999"
        size="mini"
        :disabled="formDisabled"
      >
        新增
      </button>
      <uni-card v-if="jobType == 10">
        <uni-forms label-position="top" :model="formData" label-width="100vw">
          <uni-forms-item label="有毒有害介质分析标准" name="fxsj">
            <uni-easyinput type="text" v-model="formData.ydyhwzfxbz" />
          </uni-forms-item>

          <uni-forms-item label="可燃气体分析标准" name="fxjg">
            <uni-easyinput type="text" v-model="formData.krqtfxbz" />
          </uni-forms-item>
        </uni-forms>
      </uni-card>
      <uni-card v-for="(item, index) in qitiData">
        <uni-forms
          v-if="jobType == 5 || jobType == 2"
          label-position="top"
          :model="item"
          label-width="100vw"
        >
          <uni-forms-item label="分析时间" name="fxsj">
            <uni-datetime-picker
              type="datetime"
              v-model="item.fxsj"
              :hide-second="true"
            />
          </uni-forms-item>
          <uni-forms-item
            :label="jobType == 5 ? '分析点' : '代表性气体'"
            name="dbxqt"
          >
            <uni-easyinput
              type="text"
              v-model="item.dbxqt"
              v-if="jobType == 5"
            />
            <uni-data-select
              style="border: none"
              v-model="item.dbxqt"
              v-else
              :localdata="[
                {
                  value: '可燃性气体',
                  text: '可燃性气体',
                },
                {
                  value: '有毒有害介质',
                  text: '有毒有害介质',
                },
                {
                  value: '氧气含量',
                  text: '氧气含量',
                },
              ]"
              @change="changeQt($event, item)"
            ></uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="分析结果" name="fxjg">
            <uni-easyinput
              type="text"
              v-model="item.fxjg"
              placeholder="输入完后自动补全单位"
              @change="changefxjg($event, item)"
            >
            </uni-easyinput>
          </uni-forms-item>
          <uni-forms-item label="分析人" name="fxr">
            <Qianming
              v-model="item.fxr"
              :canvasId="'fxr' + index"
              :open="openQm"
            ></Qianming>
          </uni-forms-item>
        </uni-forms>
        <uni-forms
          v-if="jobType == 10"
          label-position="top"
          :model="item"
          label-width="100vw"
        >
          <uni-forms-item label="有毒有害物质" name="dbxqt">
            <uni-easyinput type="text" v-model="item.ydyhwz" />
          </uni-forms-item>
          <uni-forms-item label="可燃气" name="dbxqt">
            <uni-easyinput type="text" v-model="item.krqt" />
          </uni-forms-item>
          <uni-forms-item label="含氧量" name="dbxqt">
            <uni-easyinput type="text" v-model="item.hyl" />
          </uni-forms-item>
          <uni-forms-item label="取样时间" name="fxsj">
            <uni-datetime-picker
              type="datetime"
              v-model="item.fxsj"
              :hide-second="true"
            />
          </uni-forms-item>
          <uni-forms-item label="分析部位" name="dbxqt">
            <uni-easyinput type="text" v-model="item.fxbw" />
          </uni-forms-item>
          <uni-forms-item label="分析人" name="fxr">
            <Qianming
              v-model="item.fxr"
              :canvasId="'fxr' + index"
              :open="openQm"
            ></Qianming>
          </uni-forms-item>
        </uni-forms>
      </uni-card>
    </view>
    <view class="btn-box">
      <button type="primary" size="default" @click="onSubmit">提 交</button>
    </view>
    <uni-popup ref="alertDialog" type="dialog">
      <uni-popup-dialog
        type="warn"
        cancelText="取消"
        confirmText="确认"
        title="提示"
        content="是否确认提交？"
        @confirm="dialogConfirm"
        @close="dialogClose"
      ></uni-popup-dialog>
    </uni-popup>
    <catSignature
      :canvasId="cId + ''"
      @close="closeQm"
      @save="saveQm"
      :visible="showQm"
      v-if="showQm"
    />
  </view>
</template>
<script>
export default {
  data() {
    return {
      num: "",
      billNumber: "",
      billType: "",
      id: null,
      pid: null,
    };
  },
  onLoad(payload) {
    if (payload.id) {
      this.pid = payload.pid;
      this.billNumber = payload.billNumber;
      return (this.id = payload.id);
    }
    this.billNumber = payload.billNumber;
    this.num = payload.num;
    this.pid = payload.pid;
    this.billType = payload.billType;
  },
};
</script>
<script setup>
import catSignature from "@/components/cat-signature.vue";
import { getUserProfile } from "@/api/user.js";
import Form from "./formv2.vue";
import { onMounted, ref, getCurrentInstance, nextTick, computed } from "vue";
import { default as zyp, optionv2, mapNavList } from "../options/index.js";
import { apis as APIS } from "@/api/zygl/zyjh.js";
import Qianming from "./qianming.vue";
import { apis } from "@/api/zygl/zyp";
import { router } from "@/router/index.js";
// import { formatDate } from "@/utils/index.js";

// 签字相关逻辑
const showQm = ref(false);
const example = ref(null);
const cId = ref(2112);
const openQm = (e) => {
  cId.value = Date.now();
  showQm.value = true;
  example.value = e;
};
const closeQm = () => {
  showQm.value = false;
};
const saveQm = (val) => {
  closeQm();
  example.value.exposed.save(val);
};
const changeQm = (option, data) => {
  if (option.qmDt) {
    if (data[option.prop]) {
      data[option.qmDt] = formatDate(Date.now());
    }
  }
};

const formatDate = (time) => {
  if (time) {
    const date = new Date(time);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const h = date.getHours();
    const m = date.getMinutes();
    return `${year}-${padZero(month)}-${padZero(day)} ${padZero(h)}:${padZero(
      m
    )}`;
  } else {
    return null;
  }
};

//补零函数
function padZero(n) {
  return n < 10 ? "0" + n : n;
}
const proxy = getCurrentInstance();
const tabCurrentIndex = ref(1);
const tabClick = (key) => {
  tabCurrentIndex.value = key;
  form.value.setOptions(formOptionV2.value[key]);
};
const longLabelSlots = ref([]); // 长label 输入框
const qianmingSlots = ref([]); // 签名插槽
const formOptions = ref([]); // 表单项
const alertDialog = ref(); // 弹窗vue实例

const dialogConfirm = () => {
  submitData();
};
const dialogClose = () => {
  alertDialog.value.close();
};

const onSubmit = async () => {
  const res = await form.value.getFormData();

  if (res === false && tabCurrentIndex.value != 4) {
    return;
  } else {
    alertDialog.value.open();
  }
};
const submitData = async () => {
  const data = await form.value.getFormData();
  let glzyps = [];
  if (data.glqtzyp && data.glqtzyp.length) {
    glzyps = zypList.value.filter((ele) => data.glqtzyp.includes(ele.value));
  }
  pc.value = judgeChangePcValue(pc.value, {
    ...data,
    qitiData: qitiData.value,
    ...formData.value,
  });
  if (!keepId.value) {
    APIS.saveBillData({
      specialNumber: billNum.value,
      ptw: billNo.value,
      content: JSON.stringify({
        ...data,
        qitiData: qitiData.value,
        ...formData.value,
      }),
      jobType: jobType.value,
      jobStartDate: data.jobDate[0],
      jobEndDate: data.jobDate[1],
      local: data.local,
      pc: pc.value,
      changeBillNumber: data.glqtzyp && data.glqtzyp.join(","),
      changeBillNumberId: glzyps.map((item) => item.id).join(","),
    }).then((res) => {
      router.back();
    });
  } else {
    apis
      .update({
        specialNumber: billNum.value,
        ptw: billNo.value,
        content: JSON.stringify({
          ...data,
          qitiData: qitiData.value,
          ...formData.value,
        }),
        jobType: jobType.value,
        jobStartDate: data.jobDate[0],
        jobEndDate: data.jobDate[1],
        id: keepId.value,
        local: data.local,
        pc: pc.value,
        changeBillNumber: data.glqtzyp && data.glqtzyp.join(","),
        changeBillNumberId: glzyps.map((item) => item.id).join(","),
      })
      .then((res) => {
        keepId.value = res.id;
        router.back();
      });
  }
};

const billNum = ref("");
const billNo = ref("");
const jobType = ref(""); //作业类型
const keepId = ref(""); // 数据id
const form = ref(); // 表单实例
const qitiData = ref([]); // 气体分析数据
const formData = ref({}); // 作业票数据
const navList = ref([]); // tab栏
const formOptionV2 = ref({});
const zyryList = ref([]);
const pc = ref(1); // 状态
// 签名步骤

const step = ref({
  point: "",
  handById: "",
  step: "",
});
// 新增气体分析
const addQtjc = () => {
  qitiData.value.push({
    fxsj: "",
    dbxqt: "",
    fxjg: "",
    fxr: "",
  });
};
const fzrId = ref("");
const jhrId = ref("");
// 加载数据方法
const initData = () => {
  const { num, billNumber, billType, id, pid } = proxy.data;
  if (id || keepId.value) {
    keepId.value = keepId.value || id;
    apis.nextStep(keepId.value).then((result) => {
      if (result.data) {
        step.value = result.data;
      }
    });
    apis.detail(keepId.value).then((res) => {
      zypData.value = res;
      pc.value = res.pc || 1;
      billNum.value = res.specialNumber;
      billNo.value = res.ptw;
      jobType.value = res.jobType;
      const option = optionv2[res.jobType];
      navList.value = mapNavList[res.jobType];
      const formData = JSON.parse(res.content);
      formData.glqtzyp =
        res.changeBillNumber && res.changeBillNumber.split(",");
      qitiData.value = formData.qitiData || [];
      form.value.setFormData(formData);
      tabCurrentIndex.value = res.pc;
      if (option) {
        formOptionV2.value = option.options;
        formOptions.value = formOptionV2.value[res.pc];
        form.value.setOptions(formOptionV2.value[res.pc]);
        longLabelSlots.value = option.longLabelSlots;
        qianmingSlots.value = option.qianmingSlots;
      }
    });
  }

  APIS.detail(pid).then((res) => {
    fzrId.value = res.custodyId;
    jhrId.value = res.jobPersonChargeId;
    try {
      zyryList.value = JSON.parse(res.jobPersonnel) || [];
    } catch (error) {
      zyryList.value = [];
    }
    if (id || keepId.value) {
      return;
    }
    billNum.value = num;
    billNo.value = billNumber;
    jobType.value = billType;
    const option = optionv2[billType];
    navList.value = mapNavList[billType];
    pc.value = 1;
    form.value.setFormData({
      titleCode: billNum.value,
      sqr: res.applyPeople,
      local: res.local,
      zynr: res.jobContent,
      jobContent: res.jobContent,
      jobApplyCompany: res.applyCompany,
      zysqdw: res.applyCompany,
      zydw: res.workShop,
      zyjhr: res.custody,
      jhr: res.custody,
      custody: res.custody,
      zyfzr: res.jobPersonCharge,
      zydwfzr: res.jobPersonCharge,
      jobDate: [
        `${res.jobPlanStartDate} ${res.jobPlanStartTime}`,
        `${res.jobPlanEndDate} ${res.jobPlanEndTime}`,
      ],
    });
    if (option) {
      formOptionV2.value = option.options;
      formOptions.value = formOptionV2.value[1];
      form.value.setOptions(formOptionV2.value[1]);
      longLabelSlots.value = option.longLabelSlots;
      qianmingSlots.value = option.qianmingSlots;
    }
  });
};
const zypData = ref({});
const userInfo = ref({});
const zypList = ref([]);
onMounted(() => {
  const { billNumber, id } = proxy.data;
  let selfId = id || "";

  getUserProfile().then((res) => {
    userInfo.value = res.data;
  });
  apis
    .getGlzyp({
      ptw: billNumber,
    })
    .then((res) => {
      zypList.value = [
        ...res
          .filter((item) => item.id != selfId)
          .map((ele) => ({
            text: ele.specialNumber,
            value: ele.specialNumber,
            id: ele.id,
          })),
      ];
    });
  initData();
});

const qmDisabled = (option) => {
  const userIds = (step.value.handById && step.value.handById.split(",")) || [];
  if (
    // (
    // tabCurrentIndex.value == 6 &&
    // (
    option.prop.includes("jsjdr") ||
    option.prop.includes("qianming1")
    // ||
    // option.prop.includes("bmjhr") ||
    // option.prop.includes("fhjhr"))) ||
    // tabCurrentIndex.value == 5
  ) {
    return false;
  } else if (
    !userIds.includes(String(userInfo.value.userId)) ||
    step.value.point != option.prop
  ) {
    return true;
  } else {
    return false;
  }
};

const formDisabled = computed(() => {
  if (pc.value >= tabCurrentIndex.value) {
    return false;
  } else {
    return true;
  }
});
// 判断是否更改数据状态方法
const judgeChangePcValue = (pc, data) => {
  // 不需判断状态
  const notNeedHanle = [1, 2, 4, 5];
  let newPc = pc;
  if (notNeedHanle.includes(pc)) {
    newPc = pc + 1;
  } else if (pc == 3) {
    let allSp = ["yjqm1", "yjqm2", "yjqm3", "yjqm4"];
    let falg = true;
    allSp.forEach((item) => {
      if (!data[item] || !falg) {
        falg = false;
      }
    });
    if (falg) {
      newPc = pc + 1;
    }
  } else if (pc == 6) {
    let falg = true;

    let allSp = ["aqjdr", "jsjdr1", "bmjhr", "fhjhr", "yjqm5", "yjqm6"];
    allSp.forEach((item) => {
      if (!data[item] || !falg) {
        falg = false;
      }
    });
    if (falg) {
      newPc = pc + 1;
    }
  }
  return newPc;
};

// 自动携带后缀
const changefxjg = (val, item) => {
  if (val.includes(item.hz)) {
    return;
  } else if (val) {
    item.fxjg = item.fxjg + item.hz;
  }
};

const changeQt = (val, item) => {
  if (val == "氧气含量") {
    item.hz = "%";
  } else if (val == "有毒有害介质") {
    item.hz = "mg/m³";
  } else {
    item.hz = "%LEL";
  }
  let jg = item.fxjg || "";
  if (jg.includes("%")) {
    jg = jg.split("%")[0];
  } else if (jg.includes("mg/m³")) {
    jg = jg.split("mg/m³")[0];
  } else if (jg.includes("%LEL")) {
    jg = jg.split("%LEL")[0];
  }
  if (item.fxjg) {
    item.fxjg = jg + item.hz;
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 16px;
  background-color: #fff !important;
}

.btn-box {
  display: flex;
  justify-content: space-between;
}

.input-num {
  display: inline-block;
  width: 50px;
  border-bottom: 1px solid #000;
  font-size: 13px;
  padding: 0 !important;
  vertical-align: middle;
}

.navbar {
  height: 40px;
  padding: 0 5px;
  background: #fff;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.06);
  position: relative;
  overflow-y: auto;
  white-space: nowrap; // 设置内容不换行

  .nav-item {
    display: inline-block;
    white-space: nowrap; // 设置内容不换行
    padding: 0 10px;
    text-align: center;
    line-height: 40px;
    height: 100%;
    font-size: 15px;
    position: relative;

    &.current {
      color: blue;

      &:after {
        content: "";
        position: absolute;
        left: 50%;
        bottom: 0;
        transform: translateX(-50%);
        width: 44px;
        height: 0;
      }
    }
  }
}
</style>
